<template>
  <div class="kb-stats">
    <div class="stats-grid">
      <!-- 文档统计卡片 -->
      <div class="stat-card">
        <div class="card-icon documents">
          <el-icon><DocumentCopy /></el-icon>
        </div>
        <div class="card-content">
          <div class="card-value">{{ kbStore.documentCount }}</div>
          <div class="card-label">文档总数</div>
        </div>
      </div>

      <!-- 类型统计卡片 -->
      <div class="stat-card">
        <div class="card-icon types">
          <el-icon><Tickets /></el-icon>
        </div>
        <div class="card-content">
          <div class="card-value">{{ kbStore.typeDistribution.length }}</div>
          <div class="card-label">文档类型</div>
        </div>
      </div>

      <!-- 向量库大小 -->
      <div class="stat-card" v-if="kbStore.stats">
        <div class="card-icon size">
          <el-icon><DataAnalysis /></el-icon>
        </div>
        <div class="card-content">
          <div class="card-value">{{ formatSize(kbStore.stats.vectorstore_size_mb) }}</div>
          <div class="card-label">向量库大小</div>
        </div>
      </div>

      <!-- 最后更新时间 -->
      <div class="stat-card">
        <div class="card-icon update">
          <el-icon><Clock /></el-icon>
        </div>
        <div class="card-content">
          <div class="card-value">{{ lastUpdate }}</div>
          <div class="card-label">最后更新</div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 文档类型分布 -->
      <div class="chart-box">
        <h3>📊 文档类型分布</h3>
        <div v-if="kbStore.typeDistribution.length > 0" ref="typeChart" class="chart"></div>
        <div v-else class="empty-chart">暂无数据</div>
      </div>

      <!-- 类型详情表格 -->
      <div class="chart-box">
        <h3>📋 类型详情</h3>
        <el-table :data="kbStore.typeDistribution" stripe style="width: 100%">
          <el-table-column prop="type" label="文档类型" width="150">
            <template #default="{ row }">
              <el-tag :type="getTypeColor(row.type)">{{ getTypeLabel(row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="数量" width="100">
            <template #default="{ row }">
              <el-text tag="strong">{{ row.count }}</el-text>
            </template>
          </el-table-column>
          <el-table-column label="占比" min-width="150">
            <template #default="{ row }">
              <el-progress
                :percentage="getPercentage(row.count)"
                :format="() => `${getPercentage(row.count)}%`"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 知识库信息 -->
    <div class="info-section">
      <h3>📖 知识库信息</h3>
      <div class="info-grid">
        <div class="info-item" v-if="kbStore.stats">
          <label>知识库状态:</label>
          <span>
            <el-tag type="success" v-if="kbStore.stats.vectorstore_exists">已初始化</el-tag>
            <el-tag v-else>未初始化</el-tag>
          </span>
        </div>
        <div class="info-item">
          <label>存储路径:</label>
          <span>{{ kbStore.stats?.kb_path || '-' }}</span>
        </div>
        <div class="info-item">
          <label>向量库路径:</label>
          <span>{{ kbStore.stats?.vectorstore_path || '-' }}</span>
        </div>
        <div class="info-item">
          <label>分割块大小:</label>
          <span>{{ kbStore.stats?.chunk_size || '-' }} 字符</span>
        </div>
        <div class="info-item">
          <label>块重叠大小:</label>
          <span>{{ kbStore.stats?.chunk_overlap || '-' }} 字符</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { DocumentCopy, Tickets, DataAnalysis, Clock } from '@element-plus/icons-vue'
import { useKnowledgeBaseStore } from '@/stores/knowledge-base'

const kbStore = useKnowledgeBaseStore()
const typeChart = ref(null)
const lastUpdate = ref('刚刚')

const typeMap = {
  workorder: '工单',
  fault_analysis: '故障分析',
  equipment_manual: '设备说明书',
  other: '其他'
}

const typeColorMap = {
  workorder: 'info',
  fault_analysis: 'warning',
  equipment_manual: 'success',
  other: 'default'
}

const formatSize = (mb) => {
  if (!mb) return '0 MB'
  return `${mb.toFixed(2)} MB`
}

const getTypeLabel = (type) => {
  return typeMap[type] || type
}

const getTypeColor = (type) => {
  return typeColorMap[type] || 'default'
}

const getPercentage = (count) => {
  const total = kbStore.documentCount
  if (total === 0) return 0
  return Math.round((count / total) * 100)
}

const updateLastTime = () => {
  const now = new Date()
  const hours = now.getHours()
  const minutes = now.getMinutes()
  lastUpdate.value = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
}

const initChart = () => {
  if (!typeChart.value || kbStore.typeDistribution.length === 0) return

  // 动态导入 ECharts
  import('echarts').then(echarts => {
    const chart = echarts.init(typeChart.value)
    const data = kbStore.typeDistribution.map(item => ({
      value: item.count,
      name: getTypeLabel(item.type)
    }))

    const option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'bottom',
        bottom: 10
      },
      series: [
        {
          name: '文档数量',
          type: 'pie',
          radius: '70%',
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }

    chart.setOption(option)

    // 响应窗口大小变化
    window.addEventListener('resize', () => {
      chart.resize()
    })
  }).catch(() => {
    console.warn('ECharts 未安装，使用简单图表展示')
  })
}

watch(
  () => kbStore.typeDistribution,
  () => {
    initChart()
  },
  { deep: true }
)

onMounted(async () => {
  updateLastTime()
  await kbStore.fetchStats()
  initChart()

  // 每分钟更新一次时间
  setInterval(updateLastTime, 60000)
})
</script>

<style scoped>
.kb-stats {
  padding: 0;
}

/* 统计卡片网格 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px;
  background: var(--el-bg-color);
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.stat-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
}

.card-icon.documents {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.card-icon.types {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.card-icon.size {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.card-icon.update {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
}

.card-content {
  flex: 1;
}

.card-value {
  font-size: 32px;
  font-weight: 700;
  color: var(--el-text-color-primary);
  margin-bottom: 5px;
}

.card-label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

/* 图表容器 */
.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.chart-box {
  background: var(--el-bg-color);
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.chart-box h3 {
  margin: 0 0 20px 0;
  color: var(--el-text-color-primary);
  font-size: 16px;
  flex-shrink: 0;
}

.chart-box :deep(.el-table) {
  background: transparent;
}

.chart-box :deep(.el-table__header) {
  background: var(--el-bg-color-page);
}

.chart {
  width: 100%;
  height: 300px;
  flex: 1;
  min-height: 0;
}

.empty-chart {
  width: 100%;
  height: 300px;
  flex: 1;
  min-height: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--el-text-color-placeholder);
  background: var(--el-bg-color-page);
  border-radius: 8px;
}

/* 信息部分 */
.info-section {
  background: var(--el-bg-color);
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.info-section h3 {
  margin: 0 0 20px 0;
  color: var(--el-text-color-primary);
  font-size: 16px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: var(--el-bg-color-page);
  border-radius: 8px;
  border-left: 3px solid var(--el-color-primary);
}

.info-item label {
  min-width: 120px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.info-item span {
  color: var(--el-text-color-secondary);
  flex: 1;
  word-break: break-all;
}

@media (max-width: 1024px) {
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
  }

  .charts-container {
    grid-template-columns: 1fr;
  }

  .chart {
    height: 250px;
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }

  .stat-card {
    flex-direction: column;
    text-align: center;
  }

  .card-value {
    font-size: 24px;
  }

  .charts-container {
    grid-template-columns: 1fr;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>

